package cn.edu.zju.gis.disasterBE.sever.service;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import cn.edu.zju.gis.disasterBE.sever.dao.weatherDao;
import cn.edu.zju.gis.disasterBE.sever.entity.weatherQuery;
import org.springframework.stereotype.Service;
@Service
public class weatherService {
    static private String extractFirstAvaliable(JSONObject jobj){
        String k = jobj.keySet().iterator().next();
        return jobj.getString(k);
    }
    public static boolean writedb(String weatherJSON,int did,double lat,double lng){
        System.out.println("writedb=============================");
        JSONObject object = JSONObject.parseObject(weatherJSON);
        JSONArray hourArray = object.getJSONArray("hours");
        for (int i = 0; i < hourArray.size(); i++){
            JSONObject itemObj = hourArray.getJSONObject(i);
            weatherQuery Q = new weatherQuery();
            Q.lat = lat;
            Q.lng = lng;
            Q.temperature = Double.parseDouble(extractFirstAvaliable(itemObj.getJSONObject("airTemperature")));
            Q.precipitation = Double.parseDouble(extractFirstAvaliable(itemObj.getJSONObject("precipitation")));
            Q.cloudCover = Double.parseDouble(extractFirstAvaliable(itemObj.getJSONObject("cloudCover")));
//            Q.windspeed = Double.parseDouble(itemObj.getJSONObject("windSpeed").getString("noaa"));
//            Q.winddirection = Double.parseDouble(itemObj.getJSONObject("windDirection").getString("noaa"));
            Q.time = itemObj.getString("time");
            Q.did = did;


            weatherDao.write(Q);
        }

        return true;
    }
}
